import os;
import os.path;
import catalogs;
import exiftool;
import threading;
import mimetypes;

class Importer(object):
    
    folders = [];
    files = [];
    filteredFiles = [];
    
    def __init__(self,catalog,thumbnailer,callbackStatus,callbackProgress,callbackEnd):
        self.catalog = catalog;
        self.callbackStatus = callbackStatus;
        self.callbackProgress = callbackProgress;
        self.callbackEnd = callbackEnd;
        self.thumbnailer = thumbnailer;
    
    def addFolder(self,folder):
        self.folders.append(folder);
        
    def addFile(self,file):
        self.files.append(file);
        
    def run(self):
        self.canceled = False;
        self.lock = threading.Lock();
        worker = threading.Thread(target=self.work);
        worker.setDaemon(True);
        worker.start();
        
    def cancel(self):
        self.lock.acquire();
        try:
            self.canceled = True;
        finally:
            self.lock.release();
            
    def isCanceled(self):
        self.lock.acquire();
        try:
            return self.canceled;
        finally:
            self.lock.release();

    def work(self):
        self.callbackStatus('Searching for importable files',None);
        for folder in self.folders:
            for root, dirs, files in os.walk(folder):
                for name in files:
                    if self.isCanceled():
                        self.callbackEnd(False);
                        return False;
                    self.queueFile(os.path.join(root,name));
        for file in self.files:
            self.queueFile(file);
        pos = 0;
        importedFiles = [];
        for file,mimetype in self.filteredFiles:
            self.callbackStatus('Processing '+str(pos)+'/'+str(len(self.filteredFiles)),file);
            pos = pos+1;
            file = self.catalog.normalizeFile(file);
            self.catalog.removeFile(file);
            self.catalog.addFile(file,mimetype);
            self.catalog.replaceTags(file,exiftool.readXmpTags(self.catalog.resolveFile(file)));
            importedFiles.append(file);
            self.callbackProgress(pos,len(self.filteredFiles));
            if self.isCanceled():
                self.callbackEnd(False);
                return False;
        self.callbackEnd(True);
        return True;
            
                        
    def queueFile(self,file):
        if os.path.exists(file):
            mimetype = mimetypes.guess_type(file, True);
            if mimetype != None and mimetype[0] != None and mimetype[0].startswith('image/'):
                self.filteredFiles.append((file, mimetype[0]));
        